﻿using Leeder.Logger;
using LeederGlobal;
using NewAndong.Business;
using NewAndong.Comm;
using NewAndong.Model;
using Sunny.UI;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NewAndong.Forms
{
    public partial class FrmTransport : UIPage
    {
        bool isLoad = true;
        AutoSizeFormClass asc = new AutoSizeFormClass();
        public LogOperate LogObj => Log.GetLogger(this.GetType());

        MaterialDirectionBLL bllMaterialDirection = new MaterialDirectionBLL();
        SignalLampDirectionBLL bllSignalLampDirection = new SignalLampDirectionBLL();
        UnpackingDirectionBLL bllUnpackingDirection = new UnpackingDirectionBLL();

        string _GroupName;

        public FrmTransport(string groupName)
        {
            _GroupName = groupName;
            InitializeComponent();
        }

        private void FrmTransport_Load(object sender, EventArgs e)
        {
            if (!isLoad)
                return;
            isLoad = false;

            Init_Control();
            RefreshDgv(_GroupName);
        }

        public void Init_Control()
        {
            dgv.AutoGenerateColumns = false;
            dgv.AllowUserToAddRows = false;
            dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgv.ReadOnly = true;
            dgv.AddColumn("序号", "ID", 10);
            dgv.AddColumn("工程名称", "LampName", 25);
            dgv.AddColumn("出发台数", "TriggerCount", 10);
            dgv.AddColumn("出发延迟台数", "TriggerDelayCount", 10);
            dgv.AddColumn("单/双/三数链", "ChainMark", 10);
            dgv.AddColumn("信号源", "SignalMark", 25);
            dgv.AddColumn("状态", "Enable", 10);

            uiPanel2.RectColor = Color.FromArgb(235, 243, 255);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission > 1)
            {
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
                return;
            }
            Edit();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission > 1)
            {
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
                return;
            }
            Edit(dgv.CurrentRow.DataBoundItem as SignalLampDirectionModel);
            RefreshDgv(_GroupName);
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission > 1)
            {
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
                return;
            }

            if (UIMessageDialog.ShowMessageDialog("确定要删除该数据吗？", UILocalize.AskTitle, true, UIStyle.Red, true, false))
            {
                var model = dgv.CurrentRow.DataBoundItem as SignalLampDirectionModel;
                bllSignalLampDirection.Delete(model);
                RefreshDgv(_GroupName);
            }
        }

        private void Edit(SignalLampDirectionModel model = null, int typeId = 0)
        {
            var unpackingList = bllUnpackingDirection.GetAllByTs();
            var materialList = bllMaterialDirection.GetModelList();
            List<SignalMarkModel> signalMarkModelList = new List<SignalMarkModel>();
            foreach (var item in unpackingList)
            {
                signalMarkModelList.Add(new SignalMarkModel() { SignalMark = item.UnpackingName });
            }
            foreach (var item in materialList)
            {
                signalMarkModelList.Add(new SignalMarkModel() { SignalMark = item.MaterialName });
            }
            var signalMarks = signalMarkModelList.Select(x => x.SignalMark).ToArray();

            string[] chainMarkTypeNames = new[] { "全部", "单链", "双链", "三链" };
            string[] statuNames = new[] { "停用", "启用" };
            UIEditOption option = new UIEditOption();
            option.AutoLabelWidth = true;
            if (model != null)
            {
                option.Text = "修改出发链(" + model.LampName + ")";
                option.AddText("LampName", "工程名称", model.LampName, true);
                option.AddInteger("TriggerCount", "出发台数", model.TriggerCount, true);
                option.AddInteger("TriggerDelayCount", "出发延迟台数", model.TriggerDelayCount, true);
                option.AddCombobox("ChainMark", "单/双/三数链", chainMarkTypeNames, int.Parse(model.ChainMark), true, true);
                option.AddCombobox("SignalMark", "信号源标识", signalMarkModelList, "SignalMark", "SignalMark", model.SignalMark==null?"": model.SignalMark);
                option.AddCombobox("Enable", "状态", statuNames, model.Enable, true, true);
            }
            else
            {
                option.Text = "新增出发链";
                option.AddText("LampName", "工程名称", null, true);
                option.AddInteger("TriggerCount", "出发台数", 0, true);
                option.AddInteger("TriggerDelayCount", "出发延迟台数", 0, true);
                option.AddCombobox("ChainMark", "单/双/三数链", chainMarkTypeNames, 0, true, true);
                option.AddCombobox("SignalMark", "信号源标识", signalMarks);
                option.AddCombobox("Enable", "状态", statuNames, 1, true, true);
            }

            UIEditForm frm = new UIEditForm(option);
            frm.ShowDialog();

            if (frm.IsOK)
            {
                if (model != null)
                {
                    model.LampName = frm["LampName"].ToString();
                    model.SignalLampMappingID = 1;
                    model.TriggerCount = int.Parse(frm["TriggerCount"].ToString());
                    model.TriggerDelayCount = int.Parse(frm["TriggerDelayCount"].ToString());
                    model.ChainMark = frm["ChainMark"].ToString();
                    model.Enable = int.Parse(frm["Enable"].ToString());
                    model.SignalMark = frm["SignalMark"].ToString();
                    model.TypeId = typeId;
                    model.TypeName = _GroupName;
                    model.RealDelayCount = "";

                    var unpacking = unpackingList.Where(x => x.UnpackingName == model.SignalMark).FirstOrDefault();
                    if (unpacking != null)
                    {
                        model.UnpackingId = unpacking.ID;
                    }
                    else
                    {
                        model.UnpackingId = 0;
                    }

                    if (bllSignalLampDirection.Update(model).IsSuccess)
                    {
                        UIMessageTip.ShowOk("设置成功");
                        LogObj.Info("拉绳灯参数设置成功(" + model.LampName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                    else
                    {
                        UIMessageBox.ShowError("设置失败！");
                        LogObj.Error("设置拉绳灯失败(" + model.LampName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                    }
                }
                else
                {
                    model = new SignalLampDirectionModel();
                    model.LampName = frm["LampName"].ToString();
                    model.SignalLampMappingID = 1;
                    model.TriggerCount = int.Parse(frm["TriggerCount"].ToString());
                    model.TriggerDelayCount = int.Parse(frm["TriggerDelayCount"].ToString());
                    model.ChainMark = frm["ChainMark"].ToString();
                    model.Enable = int.Parse(frm["Enable"].ToString());
                    model.SignalMark = signalMarks[int.Parse(frm["SignalMark"].ToString())];
                    model.TypeId = typeId;
                    model.TypeName = _GroupName;
                    model.LampDescription = _GroupName;
                    model.RealDelayCount = "";

                    var unpacking = unpackingList.Where(x => x.UnpackingName == model.SignalMark).FirstOrDefault();
                    if (unpacking != null)
                    {
                        model.UnpackingId = unpacking.ID;
                    }
                    else
                    {
                        model.UnpackingId = 0;
                    }

                    var result = bllSignalLampDirection.GetModelByNameOrSpecMark(model.LampName);
                    if (result.Count > 0)
                    {
                        UIMessageBox.ShowError("信号灯名称或信号灯重复，请检查后才添加！");
                    }
                    else
                    {
                        if (bllSignalLampDirection.Add(model).IsSuccess)
                        {
                            GolbalVariable.SignalLampDirectionBag.Add(model);
                            UIMessageTip.ShowOk("新增成功");
                            LogObj.Info("新增拉绳灯成功(" + model.LampName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                        }
                        else
                        {
                            UIMessageBox.ShowError("新增失败！");
                            LogObj.Error("新增拉绳灯失败(" + model.LampName + ");作业者:" + ApplicationCache.CurrentUser.LoginName);
                        }
                    }
                }
            }
            frm.Dispose();
            RefreshDgv(_GroupName);
        }

        private void dgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (ApplicationCache.CurrentUser.Permission > 1)
            {
                UIMessageBox.Show("该操作需要管理员权限，请先切换管理员账号！");
                return;
            }
            var dgv = (UIDataGridView)sender;
            Edit(dgv.CurrentRow.DataBoundItem as SignalLampDirectionModel);
            RefreshDgv(_GroupName);
        }

        private void RefreshDgv(string groupName)
        {
            var list = bllSignalLampDirection.GetListByGroupName(groupName);
            dgv.DataSource = null;
            dgv.DataSource = list.OrderBy(x => x.ID).ToList();
        }

        private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;

            if (e.ColumnIndex == 4)
            {
                e.FormattingApplied = true;
                DataGridViewRow row = dgv.Rows[e.RowIndex];
                if (row != null)
                {
                    if (row.Cells[e.ColumnIndex].Value.ToString() == "0")
                    {
                        e.Value = string.Format("{0}",
                          "全部");
                    }
                    else if (row.Cells[e.ColumnIndex].Value.ToString() == "1")
                    {
                        e.Value = string.Format("{0}",
                      "单链");
                    }
                    else if (row.Cells[e.ColumnIndex].Value.ToString() == "2")
                    {
                        e.Value = string.Format("{0}",
                      "双链");
                    }
                    else if (row.Cells[e.ColumnIndex].Value.ToString() == "3")
                    {
                        e.Value = string.Format("{0}",
                      "三链");
                    }
                }
            }
            if (e.ColumnIndex == 6)
            {
                e.FormattingApplied = true;
                DataGridViewRow row = dgv.Rows[e.RowIndex];
                if (row != null)
                {
                    if (row.Cells[e.ColumnIndex].Value.ToString() == "0")
                    {
                        e.Value = string.Format("{0}",
                          "停用");
                    }
                    else if (row.Cells[e.ColumnIndex].Value.ToString() == "1")
                    {
                        e.Value = string.Format("{0}",
                      "启用");
                    }
                }
            }
        }
    }
}
